/*
 * Copyright (C) 2016 Facishare Technology Co., Ltd. All Rights Reserved.
 */
package com.ciwong.mobilelib.eyeguard.permission;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.ciwong.mobilelib.R;
import com.ciwong.mobilelib.eyeguard.permission.rom.HuaweiUtils;
import com.ciwong.mobilelib.eyeguard.permission.rom.MeizuUtils;
import com.ciwong.mobilelib.eyeguard.permission.rom.MiuiUtils;
import com.ciwong.mobilelib.eyeguard.permission.rom.OppoUtils;
import com.ciwong.mobilelib.eyeguard.permission.rom.QikuUtils;
import com.ciwong.mobilelib.eyeguard.permission.rom.RomUtils;
import com.ciwong.mobilelib.widget.CWDialog;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Description:
 *
 * @author zhaozp
 * @since 2016-10-17
 */

public class FloatWindowManager {
	private static final String TAG = "FloatWindowManager";

	private static volatile FloatWindowManager instance;

	private boolean                    isWindowDismiss = true;
	private WindowManager              windowManager   = null;
	private WindowManager.LayoutParams mParams         = null;
	private CWDialog dialog;

	public static FloatWindowManager getInstance() {
		if (instance == null) {
			synchronized (FloatWindowManager.class) {
				if (instance == null) {
					instance = new FloatWindowManager();
				}
			}
		}
		return instance;
	}

	public void applyOrShowFloatWindow(Context context ) {
		if (checkPermission(context)) {
			if (mOnFloatWindowPerssionGrantListener != null) {
				mOnFloatWindowPerssionGrantListener.onPerssionGranted();
			}
		} else {
			applyPermission(context);
		}
	}
	public void applyOrShowFloatWindowOnlyCheckPerssion(Context context ) {
		if (checkPermission(context)) {
			if (mOnFloatWindowPerssionGrantListener != null) {
				mOnFloatWindowPerssionGrantListener.onPerssionGranted();
			}
		}else{
			if (mOnFloatWindowPerssionGrantListener != null) {
				mOnFloatWindowPerssionGrantListener.onPerssionNoGranted();
			}
		}
	}


	private boolean checkPermission(Context context) {
		//6.0 版本之后由于 google 增加了对悬浮窗权限的管理，所以方式就统一了
		if (Build.VERSION.SDK_INT < 23) {
			if (RomUtils.checkIsMiuiRom()) {
				return miuiPermissionCheck(context);
			} else if (RomUtils.checkIsMeizuRom()) {
				return meizuPermissionCheck(context);
			} else if (RomUtils.checkIsHuaweiRom()) {
				return huaweiPermissionCheck(context);
			} else if (RomUtils.checkIs360Rom()) {
				return qikuPermissionCheck(context);
			} else if (RomUtils.checkIsOppoRom()) {
				return oppoROMPermissionCheck(context);
			}
		}
		return commonROMPermissionCheck(context);
	}

	private boolean huaweiPermissionCheck(Context context) {
		return HuaweiUtils.checkFloatWindowPermission(context);
	}

	private boolean miuiPermissionCheck(Context context) {
		return MiuiUtils.checkFloatWindowPermission(context);
	}

	private boolean meizuPermissionCheck(Context context) {
		return MeizuUtils.checkFloatWindowPermission(context);
	}

	private boolean qikuPermissionCheck(Context context) {
		return QikuUtils.checkFloatWindowPermission(context);
	}

	private boolean oppoROMPermissionCheck(Context context) {
		return OppoUtils.checkFloatWindowPermission(context);
	}

	private boolean commonROMPermissionCheck(Context context) {
		//最新发现魅族6.0的系统这种方式不好用，天杀的，只有你是奇葩，没办法，单独适配一下
		if (RomUtils.checkIsMeizuRom()) {
			return meizuPermissionCheck(context);
		} else {
			Boolean result = true;
			if (Build.VERSION.SDK_INT >= 23) {
				try {
					Class clazz = Settings.class;
					Method canDrawOverlays = clazz.getDeclaredMethod("canDrawOverlays", Context.class);
					result = (Boolean) canDrawOverlays.invoke(null, context);
				} catch (Exception e) {
					Log.e(TAG, Log.getStackTraceString(e));
				}
			}
			return result;
		}
	}

	private void applyPermission(Context context) {
		if (Build.VERSION.SDK_INT < 23) {
			if (RomUtils.checkIsMiuiRom()) {
				miuiROMPermissionApply(context);
			} else if (RomUtils.checkIsMeizuRom()) {
				meizuROMPermissionApply(context);
			} else if (RomUtils.checkIsHuaweiRom()) {
				huaweiROMPermissionApply(context);
			} else if (RomUtils.checkIs360Rom()) {
				ROM360PermissionApply(context);
			} else if (RomUtils.checkIsOppoRom()) {
				oppoROMPermissionApply(context);
			}
		} else {
			commonROMPermissionApply(context);
		}
	}

	private void ROM360PermissionApply(final Context context) {
		showConfirmDialog(context, new OnConfirmResult() {
			@Override
			public void confirmResult(boolean confirm) {
				if (confirm) {
					QikuUtils.applyPermission(context);
				} else {
					Log.e(TAG, "ROM:360, user manually refuse OVERLAY_PERMISSION");
				}
			}
		});
	}

	private void huaweiROMPermissionApply(final Context context) {
		showConfirmDialog(context, new OnConfirmResult() {
			@Override
			public void confirmResult(boolean confirm) {
				if (confirm) {
					HuaweiUtils.applyPermission(context);
				} else {
					Log.e(TAG, "ROM:huawei, user manually refuse OVERLAY_PERMISSION");
				}
			}
		});
	}

	private void meizuROMPermissionApply(final Context context) {
		showConfirmDialog(context, new OnConfirmResult() {
			@Override
			public void confirmResult(boolean confirm) {
				if (confirm) {
					MeizuUtils.applyPermission(context);
				} else {
					Log.e(TAG, "ROM:meizu, user manually refuse OVERLAY_PERMISSION");
				}
			}
		});
	}

	private void miuiROMPermissionApply(final Context context) {
		showConfirmDialog(context, new OnConfirmResult() {
			@Override
			public void confirmResult(boolean confirm) {
				if (confirm) {
					MiuiUtils.applyMiuiPermission(context);
				} else {
					Log.e(TAG, "ROM:miui, user manually refuse OVERLAY_PERMISSION");
				}
			}
		});
	}

	private void oppoROMPermissionApply(final Context context) {
		showConfirmDialog(context, new OnConfirmResult() {
			@Override
			public void confirmResult(boolean confirm) {
				if (confirm) {
					OppoUtils.applyOppoPermission(context);
				} else {
					Log.e(TAG, "ROM:miui, user manually refuse OVERLAY_PERMISSION");
				}
			}
		});
	}

	/**
	 * 通用 rom 权限申请
	 */
	private void commonROMPermissionApply(final Context context) {
		//这里也一样，魅族系统需要单独适配
		if (RomUtils.checkIsMeizuRom()) {
			meizuROMPermissionApply(context);
		}else if(RomUtils.checkIsMiuiRom()&&RomUtils.checkIsMi3()) {
			miuiROMPermissionApply(context);
		} else{
			if (Build.VERSION.SDK_INT >= 23) {
				showConfirmDialog(context, new OnConfirmResult() {
					@Override
					public void confirmResult(boolean confirm) {
						if (confirm) {
							try {
								commonROMPermissionApplyInternal(context);
							} catch (Exception e) {
								Log.e(TAG, Log.getStackTraceString(e));
							}
						} else {
							Log.d(TAG, "user manually refuse OVERLAY_PERMISSION");
							//需要做统计效果
						}
					}
				});
			}
		}
	}

	public static void commonROMPermissionApplyInternal(Context context) throws NoSuchFieldException, IllegalAccessException {
		Class clazz = Settings.class;
		Field field = clazz.getDeclaredField("ACTION_MANAGE_OVERLAY_PERMISSION");

		Intent intent = new Intent(field.get(null).toString());
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setData(Uri.parse("package:" + context.getPackageName()));
		context.startActivity(intent);
	}

	private void showConfirmDialog(Context context, OnConfirmResult result) {
		if(context!=null){
			String msgTips = "您的手机没有授予悬浮框权限，请开启后重试。";
			String afterTips = "查看设置方法";
			CharSequence charSequence = wordDyeing(msgTips, afterTips);
			showConfirmDialog(context, charSequence, result);
		}

	}

	private void showConfirmDialog(Context context, CharSequence message, final OnConfirmResult result) {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
		}
		dialog = new CWDialog(context);
		dialog.setMessagWidePadding(message).setPositiveButton("暂不开启", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				result.confirmResult(false);
				dialog.dismiss();
				if(mOnFloatWindowPerssionGrantListener !=null){
					mOnFloatWindowPerssionGrantListener.onPerssionNoGranted();
				}
			}
		}).setNegativeButton("去开启", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(mOnFloatWindowPerssionGrantListener !=null){
					mOnFloatWindowPerssionGrantListener.onGotoGetPerssion();
				}
				result.confirmResult(true);
				dialog.dismiss();

			}
		}).setNegativeButtonTextColor(R.color.color_light_green).show();

		dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				result.confirmResult(false);
				dialog.dismiss();
				if(mOnFloatWindowPerssionGrantListener !=null){
					mOnFloatWindowPerssionGrantListener.onPerssionNoGranted();
				}
			}
		});
	}

	private interface OnConfirmResult {
		void confirmResult(boolean confirm);
	}

	public OnFloatWindowPerssionGrantListener getOnFloatWindowPerssionGrantListener() {
		return mOnFloatWindowPerssionGrantListener;
	}

	public FloatWindowManager setOnFloatWindowPerssionGrantListener(OnFloatWindowPerssionGrantListener onFloatWindowPerssionGrantListener) {
		mOnFloatWindowPerssionGrantListener = onFloatWindowPerssionGrantListener;
		return this;
	}

	OnFloatWindowPerssionGrantListener mOnFloatWindowPerssionGrantListener;
	public interface OnFloatWindowPerssionGrantListener {
		void onPerssionGranted();
		void onGotoGetPerssion();
		void onPerssionNoGranted();
		void onClickCheckSetMethod();
	}


	public CharSequence wordDyeing( String beforText, String afterText) {
		ForegroundColorSpan colorSpanBefor = new ForegroundColorSpan(Color.parseColor("#353c38"));
		ForegroundColorSpan colorSpanAfter = new ForegroundColorSpan(Color.parseColor("#52CC8F"));
		SpannableStringBuilder spannableString = new SpannableStringBuilder(beforText);
		spannableString.setSpan(colorSpanBefor,0 ,spannableString.length() , Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
		spannableString.append(afterText);
		ClickableSpan clickableSpan = new ClickableSpan() {
			@Override
			public void onClick(View widget) {
				dialog.dismiss();
				if(mOnFloatWindowPerssionGrantListener !=null){
					mOnFloatWindowPerssionGrantListener.onClickCheckSetMethod();
				}
			}

			@Override
			public void updateDrawState(TextPaint ds) {
				super.updateDrawState(ds);
				ds.setColor(Color.parseColor("#52CC8F"));
			}
		};
		spannableString.setSpan(colorSpanAfter, beforText.length(), spannableString.length() , Spanned.SPAN_INCLUSIVE_INCLUSIVE);
		spannableString.setSpan(clickableSpan
		, beforText.length(), spannableString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
		return spannableString;
	}
}
